<!-- Created by henian.xu on 2018/11/19. -->

<template>
    <div class="ship-method">
        <div
            class="out-show"
            @click="onSwitch">
            {{ areaPathName || placeholder }}
            <i
                class="f-icon"
                v-if="popupShow">&#xf106;</i>
            <i
                class="f-icon"
                v-else>&#xf107;</i>

            <template v-if="freightData.freightAmount === -1">&nbsp;| 无法配送</template>
            <template v-else-if="freightData.freightAmount">
                &nbsp;| 快递<span
                    class="price"
                >{{ freightData.freightAmount }}</span>
            </template>
        </div>

        <!-- popup -->
        <transition name="show">
            <div
                v-clickoutside="close"
                class="ship-method-popup"
                v-show="popupShow">
                <div class="body">
                    <div class="province-wrap">
                        <div
                            :class="['item',{active:provinceId === province.id}]"
                            v-for="(province) in provinceList"
                            :key="province.id"
                            @click="onProvinceItem(province)">{{ province.name }}</div>
                    </div>
                    <div
                        class="city-wrap"
                        v-if="cityList.length">
                        <div
                            :class="['item',{active:cityId === city.id}]"
                            v-for="(city) in cityList"
                            :key="city.id"
                            @click="onCityItem(city)">{{ city.name }}</div>
                    </div>
                </div>

                <div class="footer">
                    <div class="content">
                        <dl>
                            <dt>单件重量: </dt>
                            <dd>{{ weight }} 公斤/件</dd>
                        </dl>
                        <dl>
                            <dt>订购数量: </dt>
                            <dd>
                                <InputNumber
                                    :min="1"
                                    v-model="quantity"
                                    @input="onQuantityInput"/>
                            </dd>
                        </dl>
                    </div>
                    <div
                        class="freight"
                        v-if="freightData.freightAmount !== undefined">
                        <div class="label">快递</div>
                        <div v-if="freightData.freightAmount === -1">无法配送</div>
                        <div
                            class="price"
                            v-else>{{ freightData.freightAmount }}</div>
                    </div>
                </div>
                <div class="footer">
                    <div class="desc">物流可在付款时进行修改，以上罗列的地区仅为预估运费所用，并不代表此商品可实际发往所有以上地区，可实际发往的地区以下单时的可供选项为准</div>
                </div>
                <div class="footer">
                    <div class="desc">备注：以国内圆通收费为主 新疆因圆通大部分区域停发，收费按汇通标准！</div>
                </div>

            </div>
        </transition>
    </div>
</template>

<script>
import popupMixin from '~/mixins/popup.vue';
import clickoutside from '~/utils/ClickOutSide.js';
import regionCache from '../form/RegionPicker/RegionMixin';

export default {
    name: 'ShipMethod',
    mixins: [regionCache, popupMixin],
    directives: { clickoutside },
    data() {
        return {
            appLevel: true,
            provinceList: [],
            provinceId: 0,
            cityList: [],
            cityId: 0,
            // areaPathName: '',
            oldValue: null,
            quantity: 1,
            regionId: 0,
            freightData: {},
        };
    },
    props: {
        placeholder: {
            type: String,
            default: '请选择',
        },
        skuId: {
            type: Number,
            required: true,
            default: 0,
        },
        weight: {
            type: Number,
            required: true,
            default: 0,
        },
    },
    computed: {
        model: {
            get() {
                return this.value;
            },
            set(val) {
                let value = val;
                if (val.__innerInput) {
                    value = val.id;
                    // this.updateAreaPathName();
                    this.oldValue = value;
                    this.$emit('input', value);
                } else {
                    // 外部变更
                    if (this.oldValue !== value) {
                        this.init(value);
                    }
                }
            },
        },
        provinceMap() {
            return this.provinceList.reduce((p, c) => ((p[c.id] = c), p), {});
        },
        cityMap() {
            return this.cityList.reduce((p, c) => ((p[c.id] = c), p), {});
        },
        areaPathName() {
            const { provinceMap, cityMap, provinceId, cityId } = this;
            const province = provinceMap[provinceId] || {};
            const city = cityMap[cityId] || {};
            return `${province.name || ''}${city.name || ''}`;
        },
    },
    watch: {
        value: {
            handler(val) {
                // 外部的变更
                this.model = val;
            },
            immediate: process.client,
        },
    },
    methods: {
        init(val) {
            if (!val) {
                this.updateRegion();
            } else {
                this.getLoadSelectNode({ id: val }).then(json => {
                    this.provinceList = [];
                    let parentArea = { id: this.pId };
                    json.forEach(area => {
                        const selectedArea = (area => area.find(item => item.isSelect))(area);
                        this.provinceList.push({
                            ...selectedArea,
                            pId: parentArea.id,
                            children: area,
                            model: selectedArea.id,
                        });
                        parentArea = selectedArea;
                    });
                    // this.updateAreaPathName();
                });
            }
        },
        updateRegion(pId = this.pId) {
            this.getChildren({ pId, maxLv: 3 }).then(json => {
                if (pId === this.pId) {
                    this.provinceList = json;
                } else {
                    this.cityList = json;
                }
                if (!json.length) {
                    this.cityId = 0;
                    this.regionId = pId;
                }
                this.getGoodsFreightInfo();
            });
        },
        onProvinceItem(province) {
            this.regionId = this.provinceId = province.id;
            this.updateRegion(province.id);
        },
        onCityItem(city) {
            this.regionId = this.cityId = city.id;
            this.getGoodsFreightInfo();
            // this.updateRegion(area.id);
        },
        onQuantityInput() {
            this.getGoodsFreightInfo();
        },
        updateAreaPathName() {
            this.areaPathName = this.provinceList.reduce((prev, next) => (prev.push(next.name), prev), []).join('/');
        },
        onConfirm() {
            this.model = {
                ...this.provinceList[this.provinceList.length - 1],
                __innerInput: true,
            };
        },
        //**-- 运费 --**//
        getGoodsFreightInfo({ regionId = this.regionId, skuId = this.skuId, quantity = this.quantity } = {}) {
            if (!regionId || !skuId || !quantity) return;
            return this.$axios
                .get('/rpc/buyer/sp/shopFreightTemplate/getGoodsFreightInfo', { regionId, skuId, quantity })
                .then(json => {
                    const res = json.data.data;
                    this.freightData = res;
                });
        },
    },
};
</script>

<style lang="scss">
@import '~/assets/style/_index.scss';
.ship-method {
    display: inline-block;

    &-popup {
        position: absolute;
        z-index: $z-index-7;
        top: 100%;
        left: 0;
        right: 0;
        background-color: #fff;
        border: 1px solid $color-border;

        > .body {
            padding: $padding;
        }

        > .footer {
            line-height: 1.5;
            background-color: #f5f5f5;
            padding: $padding;
            border-top: 1px solid $color-border;
            @include clearfix;

            > .content {
                float: left;
                dl {
                    padding: $padding-small 0;
                    line-height: 30px;
                    @include clearfix;

                    dt {
                        float: left;
                        min-width: 6em;
                    }
                    dd {
                        overflow: hidden;
                    }
                }
            }
            > .freight {
                padding: 18px 0;
                float: right;
                width: 90px;
                height: 76px;
                background-color: #fff;
                border: 1px solid $color-border;
                text-align: center;
            }
            > .desc {
                font-size: 12px;
                color: $gray6;
            }
        }
    }
}

.province-wrap {
    @include clearfix;
    > .item {
        width: (100% / 5);
        padding: 0 $padding;
        float: left;
        cursor: pointer;
        &.active,
        &:hover {
            color: $color-main;
        }
    }
}
.city-wrap {
    @include clearfix;
    border: 1px solid #f5e0cf;
    background-color: #fff6eb;
    > .item {
        float: left;
        cursor: pointer;
        padding: 0 $padding;
        &:hover {
            color: $color-main;
        }

        &.active {
            background-color: $color-main;
            color: #fff;
        }
    }
}
</style>
